package com.zhuiyi.yiqingbackend.controller;

import com.zhuiyi.yiqingbackend.common.BaseResponse;
import com.zhuiyi.yiqingbackend.common.ErrorCode;
import com.zhuiyi.yiqingbackend.common.ResultUtils;
import com.zhuiyi.yiqingbackend.domain.Car;
import com.zhuiyi.yiqingbackend.exception.BusinessException;
import com.zhuiyi.yiqingbackend.service.CarService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/car")
@Api(value = "车辆接口", tags = "登记车辆接口")
@CrossOrigin(origins = "*", maxAge = 3600)//跨越请求配置
public class CarController {

    @Resource
    private CarService carService;

    /**
     * 获取所有车辆
     *
     */
    @GetMapping("/getAllCar")
    @ApiOperation(value = "获取所有车辆", notes = "获取所有车辆")
    public BaseResponse<List<Car>> getAllCar() {
        List<Car> allCar = carService.getAllCar();
        return ResultUtils.success(allCar);
    }

    /**
     * 添加车辆
     *
     */
    @PostMapping("/insertCar")
    @ApiOperation(value = "添加车辆", notes = "添加车辆")
    public BaseResponse<Boolean> insertCar(@RequestBody Car car) {
//        System.out.println(car);
        boolean result = carService.insertCar(car);
        if (!result) {
            throw new BusinessException(ErrorCode.INSERT_FAIL);
        }
        return ResultUtils.success(result);
    }

    /**
     * 删除车辆
     */
    @GetMapping("/deleteCar/{id}")
    @ApiOperation(value = "删除车辆", notes = "删除车辆")
    public BaseResponse<Boolean> deleteCar(@PathVariable int id) {
        boolean result = carService.deleteCar(id);
        if (!result) {
            throw new BusinessException(ErrorCode.DELETE_FAIL);
        }
        return ResultUtils.success(result);
    }

    /**
     * 更新车辆
     */
    @PostMapping("/updateCar")
    @ApiOperation(value = "更新车辆", notes = "更新车辆")
    public BaseResponse<Boolean> updateCar(@RequestBody Car car) {
        boolean result = carService.updateCar(car);
        if (!result) {
            throw new BusinessException(ErrorCode.UPDATE_FAIL);
        }
        return ResultUtils.success(result);
    }

    /**
     * 根据id获取车辆
     * @return
     */
    @GetMapping("/getCarById/{id}")
    @ApiOperation(value = "根据id获取车辆", notes = "根据id获取车辆")
    public BaseResponse getCarById(@PathVariable int id) {
        Car car = carService.getCarById(id);
        if (car == null) {
            throw new BusinessException(ErrorCode.GET_FAIL);
        }
        List list  = new ArrayList();
        list.add(car);
        return ResultUtils.success(list);
    }
}

